import React, { Component } from 'react';
import { getCartlist, addcart,lesscart } from '../api/cart'
import { NavBar } from 'antd-mobile'
import pic from '../assets/7.png'
import '../styles/Cart.scss'
class Cart extends Component {
    constructor(props) {
        super(props)
        this.state = {
            clist: []
        }
    }
  
    componentDidMount() {
        this.changecart()
    }
      //获取购物车列表
    async changecart() {
        let res = await getCartlist({ userid: localStorage.getItem('id') })
        console.log(res.data, '购物车列表');
        this.setState({
            clist: res.data.list
        })
    }

    //数量加1
    async addCart(id) {
        let res1 = await addcart({ userid: localStorage.getItem('id'), goodid: id })
        console.log(res1.data, '数量加1');
        this.changecart()
    }

    //数量减
    async lessCart(id) {
        let res1 = await lesscart({ userid: localStorage.getItem('id'), goodid: id })
        console.log(res1.data, '数量减1');
        this.changecart()
    }

    //左上角返回
    back() {
        this.props.history.goBack()
    }
    render() {
        return (
            <div className='cart'>
                <NavBar onBack={() => { this.back() }}>购物车({this.state.clist.length})</NavBar>
                <div className='goods'>
                    {
                        this.state.clist.length != 0 ?
                            this.state.clist.map((item, index) => {
                                return (
                                    <div className="gooditem" key={index}>
                                        <img src={item.pic} alt="" />
                                        <div className="text">
                                            <p className='txt'>{item.name}</p>
                                            <span className='span'>3天后原价</span>
                                            <p className='actPrice'>￥<span>{item.salesPrice.value}</span></p>
                                        </div>
                                        <div className='countchange'>
                                            <button  onClick={() =>{ this.lessCart(item.id) }}>-</button>
                                            <input type="text" value={item.count} size='1'  />
                                            <button onClick={() => { this.addCart(item.id) }}>+</button>
                                        </div>
                                    </div>
                                )
                            }) : <div>
                                <img src={pic} alt="" />
                            </div>
                    }
                </div>
            </div>
        );
    }
}

export default Cart;